package org.fujene.memoryblock;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.fujene.structure.Constants;
import org.fujene.toolbox.ByteConverter;

/**
 * 検索対象にならない文章(URL, 更新日時など)を保存しておくブロックです。
 * 
 * @author fujisaka_yusuke
 */
public class PureContentBlock extends MemoryBlock{
	private int opt_suppindex = 0;

	public PureContentBlock(int bodySize, int ID, boolean isAllocate){
		super(bodySize, ID, Constants.MEMORY_TYPE_PURECONTENT, isAllocate);
	}

	public void setContent(int ptr, String str){
		try{
			byte[] strb = str.getBytes("UTF-8");

			setBody(ByteConverter.intToByte(strb.length, STRLEN), ptr);
			ptr += STRLEN;
			setBody(strb, ptr);
		}
		catch(UnsupportedEncodingException e){}
	}

	public String getContent(int ptr){
		try{
			int strlen = ByteConverter.byteToInt(getBody(ptr, STRLEN));
			ptr += STRLEN;
			return new String(getBody(ptr, strlen), "UTF-8");
		}
		catch(UnsupportedEncodingException e){}

		return null;
	}

	public int getNewPointer(String str){
		try{
			byte[] strb = str.getBytes("UTF-8");
			int returnPtr = this.bodySize - this.bodyVacancy;
			if (this.bodyVacancy >= STRLEN + strb.length){
				this.bodyVacancy -= STRLEN + strb.length;
				return returnPtr;
			}else{
				return -1;
			}
		}
		catch(UnsupportedEncodingException e){
			return -1;
		}
	}

	public static byte[] createByteArray(String str) throws IOException{
		byte[] barray = str.getBytes("UTF-8");
		ByteArrayOutputStream stream = new ByteArrayOutputStream();

		stream.write(ByteConverter.intToByte(barray.length, STRLEN));

		stream.write(barray);

		return stream.toByteArray();
	}

	public byte[] getData() throws IOException{
		ByteArrayOutputStream stream = new ByteArrayOutputStream(this.bodySize + 4);

		stream.write(getOptionByteStream());
		stream.write(this.getBody(0, this.bodySize));

		return stream.toByteArray();
	}

	public void setData(byte[] array){
		setBody(array, 0, bodySize, 0);
	}
	
	public int getSupplementIndex(){
		return opt_suppindex;
	}

	@Override
	public int getOptionSize(){
		return 1;
	}

	@Override
	public byte[] getOptionByteStream(){
		return ByteConverter.intToByte(opt_suppindex, 4);
	}

	@Override
	public void setOption(int option, int value){
		if (option == 0) opt_suppindex = value;
	}

	@Override
	public String getClassName(){
		return new String("PureContentBlock");
	}
}
